package io.shallwe.task;

import HslCommunication.Core.Types.OperateResult;
import HslCommunication.Core.Types.OperateResultExOne;
import HslCommunication.Profinet.Siemens.SiemensPLCS;
import HslCommunication.Profinet.Siemens.SiemensS7Net;
import com.jfinal.aop.Aop;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import io.shallwe.common.model.ParameterLog;
import io.shallwe.common.model.Toc;
import io.shallwe.history.LogTocService;
import java.util.Date;
import java.util.List;

/**
 * 参数采集服务
 * @date 2019-11-03 14:06
 * @author  shallwe_wang (王小伟 shallwe_wang@sina.cn)
 */
public class ParameterCollectService {
    private LogTocService logTocService =Aop.get(LogTocService.class);
    private SiemensS7Net plc=null;

    public ParameterCollectService(){
        //初始化PLC
        plc=new SiemensS7Net(SiemensPLCS.S1500, PropKit.get("PLC","172.30.31.1"));
        plc.setConnectTimeOut(1000);
        OperateResult result=plc.ConnectServer();
        plc.SetPersistentConnection();
    }

    public void collectParamValue(){
        List<Toc> list = logTocService.listAllToc();
        Date date = new Date();
        for (Toc toc : list ) {
            OperateResultExOne<Short> result = plc.ReadInt16(toc.getAddress());
            if(result.IsSuccess) {
                ParameterLog log = new ParameterLog();
                log.setUpdateTime(date)
                        .setAddress(toc.getAddress())
                        .setCode(toc.getCode())
                        .setRemark(toc.getRemark())
                        .setUnit(toc.getUnit())
                        .setParamValue(Double.valueOf(result.Content));
                boolean success = Db.use("pg").save(toc.getTableName(), "update_time", log.toRecord());
                LogKit.warn("参数: " + toc.getRemark() + "采集" + (success ? "成功" : "失败"));
            }
        }

    }
}
